package com.libinshen.wxpay.common.util.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.libinshen.wxpay.common.util.common.PropertiesUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/***
 * 整合阿里云短信发送任务
 * @author lbs
 */
public class SmsSendCodeUtil {

    public static boolean sendCode(String phone, String code) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            return false;
        }

        //整合阿里云短信服务，设置相关参数
        DefaultProfile profile = DefaultProfile.getProfile(PropertiesUtils.REGIONID,
                PropertiesUtils.ACCESSKEYID, PropertiesUtils.SECRET);

        DefaultAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "椰子林美景景区系统");
        request.putQueryParameter("TemplateCode", "SMS_12345678");
        request.putQueryParameter("TemplateParam", "验证码${code}，您正在进行${product}身份验证，打死不要告诉别人哦！");

        //验证码
        Map<String, Object> param = new HashMap();
        param.put("code", code);
        param.put("product", phone);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println("短信发送中，返回数据：" + response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}